package com.yhx.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.yhx.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/user/add")
    public boolean addUser(){
        return true;
    }

    @GetMapping("/user/queryUser/{id}")
    public User queryUser(@PathVariable("id") Integer id){
        User user = new User();
        user.setId(id);
        user.setName("小明");
        return user;
    }

    @GetMapping("/user/queryUsers")
    public List<User> queryUsers(){
        return null;
    }


    @GetMapping("/user/queryUserByName/{name}")
    //@HystrixCommand(fallbackMethod = "hystrixQueryUserByName")
    public List<User> queryUserByName(@PathVariable("name") String name){
        List<User> users = new ArrayList<User>();
        User user = new User();
        user.setId(1);
        user.setName(name);

        User user1 = new User();
        user1.setId(2);
        user1.setName(name);

        User user2 = new User();
        user2.setId(3);
        user2.setName(name);

        users.add(user);
        users.add(user1);
        users.add(user2);
        return users;
    }

    public List<User> hystrixQueryUserByName(String name){
        List<User> users = new ArrayList<User>();
        User user = new User().setId(0).setName("查询"+name+"时，服务发生了熔断");
        users.add(user);
        return users;
    }


    public void serviceUrl(){
        //获取服务名称
        List<String> services = discoveryClient.getServices();
        services.stream().forEach(System.out::println);
        //获取指定服务实例的URI
        List<ServiceInstance> instances = discoveryClient.getInstances("springcloud-provider");
        instances.stream().forEach(x -> System.out.println(x.getUri()));
    }
}
